
<template>
  <div class="login box-border min-h-screen px-16px pt-96px">
    <image class="absolute bottom-0 left-0 right-0 top-0 h-100% w-100% -z-1" :src="`${cdnUrl1}/imgs/xy/login/bg.png${imgVersion}`" mode="scaleToFill" />
    <div>
      <div class="ml-24px text-36px text-hex-212424">HELLO</div>
      <div class="ml-24px text-20px font-bold text-hex-A69779">欢迎来到心悦健康</div>
      <!-- 表单填写 -->
      <div class="relative mt-62px h-547px">
        <image class="absolute bottom-0 left-0 right-0 top-0 h-100% w-100% -z-1" :src="`${cdnUrl1}/imgs/xy/login/tab.png${imgVersion}`" mode="scaleToFill" />
        <div class="flex justify-around py-16px text-18px font-bold text-hex-7A756D">
          <div v-for="item in tabList" :class="{ 'text-hex-FF8B00': currentTabIndex === item.index }" @click="changeTab(item.index)">{{ item.text }}</div>
        </div>
        <uni-forms ref="baseForm" :modelValue="formData">
          <uni-forms-item class="m-24px">
            <uni-easyinput v-model="formData.phone" placeholderStyle="color:#B0B7B9" :inputBorder="false" class="bg-hex-F9F9F9" placeholder="请输入手机号" />
          </uni-forms-item>
          <uni-forms-item class="m-24px bg-hex-F9F9F9">
            <uni-easyinput v-model="formData.smsCode" placeholderStyle="color:#B0B7B9" :inputBorder="false" class="bg-hex-F9F9F9" placeholder="请输入验证码" />
          </uni-forms-item>
          <div class="mx-24px mt-16px rounded-8px bg-hex-FFD199 px-131px py-15px text-hex-ffffff">登录</div>
          <div class="mx-24px mt-12px rounded-8px bg-hex-F9F9F9 px-131px py-15px text-hex-FFD199">注册</div>
        </uni-forms>
        <image class="absolute bottom-0 left-0 right-0 top-0 h-100% w-100% -z-1" :src="`${cdnUrl1}/imgs/xy/login/tab${currentTabIndex}.png${imgVersion}`" mode="scaleToFill" />
        <div class="mx-32rpx mt-56rpx flex items-center">
          <radio :value="'0'" color="#FF8B00" :checked="checked" @click="checked=!checked" />
          <div>
            <text>登录代表您已同意</text>
            <text class="text-hex-FF8B00" @click.stop="navGoTo('/pages-square/protocol?type=1')">《用户隐私协议》</text>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import jwt_decode from 'jwt-decode'
import { useLoginStore } from '@/stores/login'

onShareAppMessage((res) => {
  return { title: '心悦' }
})
const title = '登录'
let popup: any = $ref(null)

let tabList: any = $ref([
  { index: 1, text: '手机号登录' },
  { index: 2, text: '账号密码' },
])
let currentTabIndex: any = $ref(1)
const changeTab = (index) => {
  currentTabIndex = index
}

let formData: any = $ref({
  phone: '',
  smsCode: '',
})

let baseForm: any = $ref(null)

const closePop = () => {
  popup.close()
}
const checked = $ref(false)
let nickname: any = $ref('')
const inputBlur = (e) => {
  nextTick(() => {
    nickname = e.detail.value
  })
}
let avatarOrig = $ref(`${cdnUrl}/imgs/square/header.png${imgVersion}`)
let avatarUrl = $ref('')
let avatarBase64: any = $ref('')
const onChooseAvatar = async (e) => {
  nextTick(() => {
    avatarUrl = e.detail.avatarUrl
    urlTobase64(avatarUrl).then(res => {
      avatarBase64 = res
    })
  })
}
const loginStore = useLoginStore()
//微信登录
// const wxLogin = async () => {
//   if (!checked) {
//     uni.showToast({ title: '请同意条款！', icon: 'error' })
//     return
//   }
//   const reqData: any = { provider: 'weixin' }
//   const { errMsg, code } = await login(reqData)
//   if (isNotNilOrEmpty(code)) {
//     const loginUrl = '/api/auth/wxlogin/'
//     const { status, data } = await Fetch(`${loginUrl}${code}`)
//     if (status !== 200 || data.code !== 0) {
//       popup.open('bottom')
//       return
//     }
//     const token = data.result
//     if (isNotNilOrEmpty(token)) {
//       loginStore.setToken(token)
//       const pageUrl = uni.getStorageSync('pageScene')
//       if (pageUrl) {
//         uni.removeStorageSync('pageScene')
//         uni.navigateTo({ url: pageUrl })
//       } else {
//         uni.reLaunch({ url: '/pages/health' })
//       }
//     }
//   } else {
//     console.log(errMsg)
//   }
// }
const wxLogin = async () => {
  if (!checked) {
    uni.showToast({ title: '请同意条款！', icon: 'error' })
    return
  }
  if (!loginStore.roleId) {
    popup.open('bottom')
    return
  }
  navTo('/pages/index')
}
//判断是否显示获取手机号 按钮

const isGetPhoneNumbeBtn = $computed(() => {
  return !(isNilOrEmpty(avatarBase64) || isNilOrEmpty(nickname))
})
const onGetPhoneNumbe = async (phoneNumber) => {
  if (phoneNumber.detail.encryptedData && phoneNumber.detail.iv) {
    const { code: telCode } = phoneNumber.detail
    const reqData: any = { provider: 'weixin' }
    const { errMsg, code } = await login(reqData)
    if (isNotNilOrEmpty(code)) {
      const reqData = {
        method: 'post',
        data: { code, avatar_url: avatarBase64, nickname },
      }
      const regUrl = '/api/auth/wxregister/'
      const { status, data } = await Fetch(regUrl, reqData)
      if (status !== 200 || data.code !== 0) {
        return
      }
      uni.showLoading({ title: 'Loading...' })
      const token = data.result
      if (isNotNilOrEmpty(token)) {
        const { data, status } = await Fetch(`/api/auth/wxphonenumber/${telCode}`, { method: 'get', headers: { token } })
        if (status === 200 && data.code === 0) {
          const reqData: any = { provider: 'weixin' }
          const { code } = await login(reqData)
          const loginUrl = '/api/auth/wxlogin/'
          const { status: newstatus, data: newdata } = await Fetch(`${loginUrl}${code}`)
          if (newstatus !== 200 || newdata.code !== 0) {
            return
          }
          let newToken = newdata.result
          uni.hideLoading()
          loginStore.setToken(newToken)
          const decoded: any = jwt_decode(newToken)
          loginStore.setUid(decoded.userId)
          loginStore.setRoleId(decoded?.roleId)
          const pageUrl = uni.getStorageSync('pageScene')
          if (pageUrl) {
            uni.removeStorageSync('pageScene')
            uni.navigateTo({ url: pageUrl })
          } else {
            goBack()
          }
        }
        uni.hideLoading()
      }
    } else {
      console.log(errMsg)
    }
  } else {
    uni.showToast({ title: '手机号授权失败！', icon: 'error' })
  }
}
// 微信注册
const wxRegister = async () => {
  if (isNilOrEmpty(avatarBase64)) {
    uni.showToast({ title: '请选择头像！', icon: 'error' })
    return
  }
  if (isNilOrEmpty(nickname)) {
    uni.showToast({ title: '请填写昵称！', icon: 'error' })
  }
}

const urlTobase64 = (img) => {
  if (/^https?:/.test(img)) {
    return new Promise((resolve, reject) => {
      uni.downloadFile({
        url: img,
        success(res) {
          uni.getFileSystemManager().readFile({
            filePath: res.tempFilePath, //选择图片返回的相对路径
            encoding: 'base64', //编码格式
            success: res => { //成功的回调
              resolve(`data:image/png;base64,${res.data}`)
            },
          })
        },
      })
    })
  } else {
    return new Promise((resolve, reject) => {
      uni.getFileSystemManager().readFile({
        filePath: img, //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => { //成功的回调
          resolve(`data:image/png;base64,${res.data}`)
        },
      })
    })
  }
}

const navGoTo = (url) => {
  uni.navigateTo({
    url,
  })
}
const goBack = () => {
  if (loginStore.isBack) {
    uni.navigateBack({ delta: 1 })
    loginStore.setIsBack(false)
  } else {
    reLanchTo('/pages/index')
  }
}
onMounted(() => {

})
</script>

<style lang="scss">
// ::v-deep uni-page-wrapper {
//   background: #f5f5f5;
// }

::v-deep .uni-input-input{
  // background-color: #f5f5f5;
  color: #212424;
  border-radius: 8px;
  padding: 12px;
}

::v-deep view {
  // border-top-left-radius: 64rpx !important;     /* 左上角 */
  // border-top-right-radius: 64rpx !important;    /* 右上角 */
}

// ::v-deep button{
//   margin-left: 0rpx;
// }

// ::v-deep button::after {
//   content: ' ';
//   width: 200%;
//   height: 200%;
//   position: absolute;
//   top: 0;
//   left: 0;
//   border: 1px solid #f5f5f5  !important;
//   color:#999;
//   transform-origin: 0 0;
//   box-sizing: border-box;
//   border-radius: 10px;
// }
</style>
